In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.
The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
#import libraries
import matplotlib.pyplot as plt
%matplotlib inline
import matplotlib.gridspec as gridspec
import numpy.random as rnd
import pickle
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow.contrib.layers as layers
# Load pickled data
training_file = 'data/train.p'
validation_file = 'data/valid.p'
testing_file = 'data/test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.
# Number of training examples
n_train = X_train.shape[0]
# Number of validation examples
n_validation = X_valid.shape[0]
# Number of testing examples.
n_test = X_test.shape[0]
# What's the shape of a traffic sign image?
image_shape = X_train[0].shape
# How many unique classes/labels there are in the dataset.
n_classes = len(np.unique(y_train))
print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Number of validation examples =", n_validation)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
def plot_random_samples(images, labels, n=10):
'''A function to plot random samples for
labels 0-42 in a horizontal grid'''
for label in np.unique(labels):
ids, = np.where(labels==label)
sample_ids = rnd.randint(0,len(ids),n)
samples = images[sample_ids]
gs = gridspec.GridSpec(1,10,top=1., bottom=0., right=1., left=0., hspace=0.05,wspace=0.05)
for index,g in enumerate(gs):
ax = plt.subplot(g)
ax.set_title(label)
ax.imshow(samples[index])
ax.set_xticks([])
ax.set_yticks([])
plt.show()
plot_random_samples(X_train, y_train)
## Plot the histogrm of all images.
## The histogram is computed by averaging pixel intensities over all three channels.
def hist_img_data(X):
plt.hist(np.mean(X,axis=3).flatten(),bins=range(256),color='k',density=True)
plt.xlabel('intensity(I)')
plt.ylabel('fraction of all pixels with intensity =(I)')
plt.show()
#Cumulative histogram
plt.hist(np.mean(X,axis=3).flatten(),bins=range(256),color='r',density=True,cumulative=True, histtype='step')
plt.xlabel('intensity(I)')
plt.xticks([50,100,150,200,250],['very dark', 'dark', 'medium','light','very light'])
plt.ylabel('fraction of all pixels with intensity <=(I)')
plt.show()
hist_img_data(X_train)
## Plot frequency of each type of traffic sign in the training data.
def hist_labels(datasets=None,ylabels=None):
fig = plt.figure(figsize=(16,4))
for i in range(len(datasets)):
axis = fig.add_subplot(1,3,i+1)
axis.hist(datasets[i],bins=range(n_classes+1),color='k')
plt.ylabel('#{} Samples'.format(ylabels[i]))
plt.xlabel('Traffic Sign ID')
fig.subplots_adjust(wspace=0.5)
plt.suptitle("Sample Distribution by Class")
plt.show()
hist_labels(datasets = [y_train,y_valid, y_test],ylabels = ['train','valid','test'])
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.
Other pre-processing steps are optional. You can try different techniques to see if it improves performance.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include
### converting to grayscale, etc.
import cv2
def hist_equalize(X):
'''A function to equalize the intensities across all 3 channels'''
for i in range(X.shape[0]):
img_rgb = X[i,:,:,:]
img_yuv = cv2.cvtColor(img_rgb,cv2.COLOR_RGB2YUV)
img_yuv[:,:,0] = cv2.equalizeHist(img_yuv[:,:,0])
X[i,:,:,:] = cv2.cvtColor(img_yuv,cv2.COLOR_YUV2RGB)
return X
X_train = hist_equalize(X_train)
X_valid = hist_equalize(X_valid)
X_test = hist_equalize(X_test)
#Plot the histogram after equalizing the intensities
hist_img_data(X_train)
#Plot the samples from histogram equalized images
plot_random_samples(X_train, y_train)
#Define functions that implement data augmentation here
MIN_ROTATION = -10.0
MAX_ROTATION = 10.0
MIN_OFFSET = -2
MAX_OFFSET = 2
MIN_PIXEL_POSITION = 12
MAX_PIXEL_POSITION = 20
def apply_random_affine(img,n):
'''Rotate and translate images'''
# Allocate an array for holding all transformed images.
output = np.zeros(shape=[n,*img.shape],dtype=img.dtype)
# Generate random centers and angles for rotation.
angles = (MAX_ROTATION-MIN_ROTATION) * np.random.random(n) + MIN_ROTATION
centers= np.random.randint(MIN_PIXEL_POSITION,MAX_PIXEL_POSITION+1,size=[n,2])
# Generate random offsets for translation.
offsets = np.random.randint(MIN_OFFSET,MAX_OFFSET+1,size=[n,2])
# Generate transformed copies of input image.
for i in range(n):
M_rotate = cv2.getRotationMatrix2D(tuple(centers[i]),angles[i],1)
tmp = cv2.warpAffine(img,M_rotate,None)
M_translate = np.float32([[1, 0, offsets[i,0]], [0, 1, offsets[i,1]]])
output[i] = cv2.warpAffine(tmp,M_translate,img.shape[:2])
return output
def add_variants(X,y,n_copies):
#Initialize output dataset with original data.
X_out = np.copy(X)
y_out = np.copy(y)
# Generate copies for every image in the original dataset.
# Append these copies and corresponding labels to output dataset.
m = len(X)
for i in range(m):
variant_data = apply_random_affine(X[i],n_copies)
X_out = np.vstack((X_out,variant_data))
variant_labels = np.array([y[0]]*n_copies,dtype=y.dtype)
y_out = np.concatenate((y_out,variant_labels))
return (X_out,y_out)
def augment_data(X,y,MIN_EXAMPLE_COUNT = 1000):
# Get sample count for every class label.
# For np.histogram to work correctly with 0-based labels,
# the number for bins has to be 1 more than the number of
# classes.
counts, labels = np.histogram(y,bins=range(n_classes+1))
# Initilize empty output arrays. These will be filled with
# original and transformed samples.
data_shape = X.shape[1:]
data_type = X.dtype
label_shape = y.shape[1:]
label_type = y.dtype
X_out = np.empty(shape=[0,*data_shape],dtype=data_type)
y_out = np.empty(shape=[0,*label_shape],dtype=label_type)
# For every class, generate an appropriate number of synthetic samples.
# np.histogram() above will generate one extra label
# that we don't iterate over.
for label in labels[:-1]:
X_label = X[y==label]
y_label = y[y==label]
n_orig = len(y_label)
if(counts[label] < 0.5 * MIN_EXAMPLE_COUNT):
n_copies = MIN_EXAMPLE_COUNT//counts[label]
X_label,y_label = add_variants(X_label,y_label,n_copies)
n_total = len(y_label)
X_out = np.concatenate((X_out,X_label))
y_out = np.concatenate((y_out,y_label))
print("Class label {}, original sample count {}, updated sample count {}"\
.format(label,n_orig,n_total))
return (X_out, y_out)
#Augment the data up to at least 5000 variants for each label
X_train, y_train = augment_data(X_train,y_train,MIN_EXAMPLE_COUNT=5000)
# Normalize the pixel values for train, validate and test sets
# Calculate per-channel pixel mean and std deviation.
pixel_means = np.mean(X_train,axis=(0,1,2),dtype=np.float32)
pixel_stddevs = np.std(X_train,axis=(0,1,2),dtype=np.float32)
X_train_norm = X_train - pixel_means
X_train_norm = X_train_norm / (pixel_stddevs + 1e-6) #avoid division by 0
X_valid_norm = X_valid - pixel_means
X_valid_norm = X_valid_norm / (pixel_stddevs + 1e-6) #avoid division by 0
X_test_norm = X_test - pixel_means
X_test_norm = X_test_norm / (pixel_stddevs + 1e-6) #avoid division by 0
# Wrappers for conv, maxpool, flatten and dense layers.
def conv(X,W,b,stride=1):
out = tf.nn.conv2d(X,W,[1,stride,stride,1],padding='VALID')
out = tf.nn.bias_add(out,b)
return tf.nn.relu(out)
def maxpool(X,k,s):
return tf.nn.max_pool(X,ksize=[1,k,k,1],strides=[1,s,s,1],padding='VALID')
def flatten(X):
return layers.flatten(X)
def dense(x,W,B,squash=True):
out = tf.matmul(x,W)
out = tf.add(out,B)
if squash == True:
out = tf.nn.relu(out)
return out
# Define hyper-parameters.
epochs = 130
batch_size = 128
learning_rate = 0.001
dropout_probability = 0.3
# Build LeNet like convolution network.
# Mean and std. deviation for randomly initilized parameters.
mu = 0
sigma = 0.1
# Define input plaeholders.
X = tf.placeholder(tf.float32,[None,32,32,3])
y = tf.placeholder(tf.uint8,[None])
keep_prob = tf.placeholder(tf.float32)
# Define parameters (weights and biases)
params = {
# 5x5 convolution, input depth 3, output depth 6.
'conv1':{
'weights':tf.Variable(tf.truncated_normal([5,5,3,6],mu,sigma)),
'biases' :tf.Variable(tf.zeros([6])),
'stride':1
},
# 2x2 pooling
'pool1':{
'kernel_sz':2,
'stride':2
},
# 5x5 convolution, input depth 6, output depth 16.
'conv2':{
'weights':tf.Variable(tf.truncated_normal([5,5,6,16],mu,sigma)),
'biases':tf.Variable(tf.zeros([16])),
'stride':1
},
# 2x2 pooling
'pool2':{
'kernel_sz':2,
'stride':2
},
# 400 -> 120 dense layer
'dense1':{
'weights':tf.Variable(tf.truncated_normal([400,120],mu,sigma)),
'biases':tf.Variable(tf.zeros([120]))
},
# 120 -> 84
'dense2':{
'weights':tf.Variable(tf.truncated_normal([120,84],mu,sigma)),
'biases':tf.zeros(([84]))
},
# 84 -> 43
'dense3':{
'weights':tf.Variable(tf.truncated_normal([84,43],mu,sigma)),
'biases':tf.zeros(([43]))
}
}
conv1_out = conv(X,params['conv1']['weights'],params['conv1']['biases'],params['conv1']['stride'])
pool1_out = maxpool(conv1_out,params['pool1']['kernel_sz'],params['pool1']['stride'])
conv2_out = conv(pool1_out,params['conv2']['weights'],params['conv2']['biases'],params['conv2']['stride'])
pool2_out = maxpool(conv2_out,params['pool2']['kernel_sz'],params['pool2']['stride'])
flat_out = flatten(pool2_out)
fc1_out = dense(flat_out,params['dense1']['weights'],params['dense1']['biases'])
fc1_out = tf.nn.dropout(fc1_out,keep_prob)
fc2_out = dense(fc1_out,params['dense2']['weights'],params['dense2']['biases'])
fc2_out = tf.nn.dropout(fc2_out,keep_prob)
fc3_out = dense(fc2_out,params['dense3']['weights'],params['dense3']['biases'],squash=False)
logits = fc3_out
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
one_hot_y = tf.one_hot(y,n_classes,on_value=1,off_value=0)
# Define cost function (minimization objective) and minimization algorithm.
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits,labels=one_hot_y)
training_loss = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate)
optimization = optimizer.minimize(training_loss)
# Define accuracy.
correct_predictions = tf.equal(tf.argmax(logits,1),tf.argmax(one_hot_y,1))
accuracy_calculation = tf.reduce_mean(tf.cast(correct_predictions,tf.float32))
# Define evalution function.
def evaluate(sess,X_data,y_data):
num_examples = X_data.shape[0]
net_accuracy = 0.0;
n_batches = num_examples // batch_size
for offset in range(0,num_examples,batch_size):
X_batch = X_data[offset:offset+batch_size]
y_batch = y_data[offset:offset+batch_size]
batch_accuracy = sess.run(accuracy_calculation,feed_dict={X:X_batch,y:y_batch,keep_prob:1.0})
net_accuracy += batch_accuracy
return net_accuracy / n_batches
# Define training function
from sklearn.utils import shuffle
from tqdm import tqdm
def train(sess):
sess.run(tf.global_variables_initializer())
for e in tqdm(range(epochs)):
global X_train, X_train_norm, y_train
X_train, X_train_norm, y_train = shuffle(X_train, X_train_norm,y_train)
for offset in range(0,n_train,batch_size):
X_batch = X_train_norm[offset:offset+batch_size]
y_batch = y_train[offset:offset+batch_size]
sess.run(optimization,feed_dict={X:X_batch,y:y_batch,keep_prob:1-dropout_probability})
if (e+1) % 10 == 0:
train_accuracy = evaluate(sess,X_train_norm,y_train)
valid_accuracy = evaluate(sess,X_valid_norm,y_valid)
print("Epochs {}, training accuracy {:.3f}, validation accuracy {:.3f}"\
.format(e+1,train_accuracy,valid_accuracy))
model_file_prefix = './saved_model'
def run_training(sess):
print("Training started!")
train(sess)
print("Training completed!")
print("Evaluating model on test data...")
print("Test accuracy {:.3f}".format(evaluate(sess,X_test_norm,y_test)))
print("Saving model data to file...")
saver = tf.train.Saver()
saver.save(sess,model_file_prefix)
print("Model saved!")
# Run training or load exiting model.
import os
use_existing = False
session = tf.Session(config=tf.ConfigProto(log_device_placement=True))
if use_existing == False:
run_training(session)
elif (use_existing == True) and (not os.path.isfile(model_file_prefix+'.meta')):
print("Saved model file doens't exist! Running training again...")
run_training(session)
else:
#Load saved model.
print("Reloading existing model...")
saver = tf.train.Saver()
saver.restore(session,tf.train.latest_checkpoint('.') )
print("Model loading finished!")
# Compute key metrics.
from tqdm import tqdm
def compute_key_metrics(sess,X_data,y_data):
confusion_matrix = np.zeros([n_classes,n_classes],np.int32)
predicted_labels = np.zeros_like(y_data)
n_examples = X_data.shape[0]
for offset in tqdm(range(0,n_examples,batch_size)):
X_batch = X_data[offset:offset+batch_size]
y_batch = y_data[offset:offset+batch_size]
y_predicted = sess.run(tf.argmax(logits,1),feed_dict={X:X_batch, y:y_batch, keep_prob:1.0})
np.add.at(confusion_matrix,[y_batch,y_predicted],1)
predicted_labels[offset:offset+batch_size] = y_predicted
# True positives live on the main diagonal. Extract them.
true_postives = confusion_matrix[[range(n_classes)],[range(n_classes)]]
# For false positives take column-wise sum excluding the row of the target class.
false_positives = np.sum(confusion_matrix,axis=0) - true_postives
# For false negatives take row-wise sum exclding the column of the target class.
false_negatives = np.sum(confusion_matrix,axis=1) - true_postives
# True negatives are all values in the matrix excluding the row and column of a class.
true_negatives = np.sum(confusion_matrix) - (true_postives+false_positives+false_negatives)
precision = np.squeeze(true_postives / (true_postives+false_positives+1e-6))
recall = np.squeeze(true_postives / (true_postives+false_negatives+1e-6))
specificity = np.squeeze(true_negatives / (true_negatives+false_positives+1e-6))
return {'confmat':confusion_matrix, 'predicted_labels':predicted_labels, 'precision':precision,'recall':recall, 'specificity':specificity}
metrics = compute_key_metrics(session,X_test_norm,y_test)
#Read in sign names from signnames.csv
import pandas
sign_names = pandas.read_csv('signnames.csv')
sign_names = sign_names.as_matrix()
predicted_labels = metrics['predicted_labels']
# Plot first 100 mis-classified images
misclassified_idx = np.where(np.not_equal(y_test,metrics['predicted_labels']))
M = X_test[misclassified_idx][:100]
gs = gridspec.GridSpec(25, 4,top=8., bottom=0., right=2., left=0., hspace=1,wspace=0.05)
for i,g in enumerate(gs):
ax = plt.subplot(g)
ax.imshow(M[i])
ax.set_title("Actual {}\nPredicted {}".format(sign_names[y_test[misclassified_idx][i]][1],
sign_names[predicted_labels[misclassified_idx][i]][1]))
ax.set_xticks([])
ax.set_yticks([])
plt.show()
# Plot precision and recall for all classes
plt.bar(range(n_classes),metrics['precision'])
plt.title('precision')
plt.show()
plt.bar(range(n_classes),metrics['recall'])
plt.title('recall')
plt.show()
# Print low precision and low recall classes
low_precision_classes = np.argsort(metrics['precision'])[:3]
low_recall_classes = np.argsort(metrics['recall'])[:3]
print("Low precision classes:",low_precision_classes)
print("Low recall classes:",low_recall_classes)
# Get a copy of the confusion matrix excluding true positives.
conf_mat = np.copy(metrics['confmat'])
np.fill_diagonal(conf_mat,0)
# For each class with low precision get class that causes most false positives.
false_positive_classes = np.argmax(conf_mat[:,low_precision_classes], axis=0)
print("False positive classes:",false_positive_classes)
# For each class with low recall get class that causes most false negatives.
false_negative_classes = np.argmax(conf_mat[low_recall_classes,:],axis=1)
print("False negative classes:",false_negative_classes)
# Plot and compare actual and predicted image classes with low precision
for i in range(len(low_precision_classes)):
# Get misclassified samples from false positive class.
fp_idx = np.logical_and(np.squeeze(y_test==false_positive_classes[i]),
np.squeeze(predicted_labels== low_precision_classes[i]))
fp_samples = X_test[fp_idx]
# Get (representative) samples from the target class.
target_idx = np.where(y_test == low_precision_classes[i] )
target_samples = X_test[target_idx]
print("Actual class:",sign_names[false_positive_classes[i]])
plot_random_samples(fp_samples,8)
print("Predicted as class:",sign_names[low_precision_classes[i]])
plot_random_samples(target_samples,8)
print("\n\n")
# Plot and compare actual and predicted image classes with low recall
for i in range(len(low_recall_classes)):
# Get misclassified samples from target class.
target_idx = np.logical_and(np.squeeze(y_test==low_recall_classes[i]),
np.squeeze(predicted_labels== false_negative_classes[i]))
target_samples = X_test[target_idx]
# Get (representative) samples from the false negative class.
fp_idx = np.where(y_test == false_negative_classes[i] )
fp_samples = X_test[fp_idx]
print("Actual class:",sign_names[low_recall_classes[i]])
plot_random_samples(target_samples,8)
print("Predicted as class:",sign_names[false_negative_classes[i]])
plot_random_samples(fp_samples,8)
print("\n\n")
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
# Load the images and plot them here.
import scipy.ndimage as ndimage
web_files=['web_images/bumpy.jpg','web_images/100kmspeed.jpg','web_images/caution-roadworks.jpg','web_images/no-vehicles.jpg','web_images/TurnRightAhead.jpg']
X_web = np.zeros([len(web_files),32,32,3],dtype=np.uint8)
y_web = np.array([22,7,25,15,33],dtype=np.uint8)
for i in range(len(web_files)):
X_web[i] = ndimage.imread(web_files[i])
plt.figure(figsize=(1,1))
plt.imshow(X_web[i])
plt.title(web_files[i])
plt.show()
# Run the predictions here and use the model to output the prediction for each image.
# Make sure to pre-process the images with the same pre-processing pipeline used earlier.
X_web = hist_equalize(X_web)
X_web_norm = X_web - pixel_means
X_web_norm = X_web_norm / (pixel_stddevs + 1e-6) #avoid division by 0
web_metrics = compute_key_metrics(session,X_web_norm,y_web)
### Calculate the accuracy for these 5 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
print("Acuracy for web images: ",np.sum(web_metrics['predicted_labels']==y_web)/len(y_web))
For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.
The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.
tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tf.nn.top_k is used to choose the three classes with the highest probability:
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
top5 = session.run(tf.nn.top_k(tf.nn.softmax(logits),5), feed_dict={X:X_web_norm,y:y_web,keep_prob:1.0})
for i in range(len(y_web)):
print("Actual label: {}".format(sign_names[y_web[i]]))
print("Predicted classes and probabilities ",list(zip(top5[1][i],np.round(top5[0][i],2))))
plt.figure(figsize=(1,1))
plt.imshow(X_web[i])
plt.title(web_files[i])
plt.show()
plt.figure(figsize=(2,2))
plt.bar(range(5),top5[0][i])
plt.title("Actual label: {}".format(sign_names[y_web[i]]))
plt.xticks(range(5),sign_names[top5[1][i]],rotation='vertical')
plt.show()
print("-----------------------------------------------------")
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.